import pytest
import mysql.connector
from decimal import Decimal
from redis.cluster import RedisCluster
from redis.cluster import ClusterNode

import requests

# MySQL 配置
MYSQL_HOST = "192.168.66.110"
MYSQL_PORT = 3306
MYSQL_USER = "test-superex"
MYSQL_PASSWORD = "TEST_Jd4W3zIYZmUboJZ"
MYSQL_DATABASE = "superex_trade"  # 替换为实际的数据库名

# Redis 配置
REDIS_NODES = [
    ClusterNode("192.168.66.119", 16379),
    ClusterNode("192.168.66.119", 16378),
    ClusterNode("192.168.66.119", 16377),
    ClusterNode("192.168.66.119", 16376),
    ClusterNode("192.168.66.119", 16375),
    ClusterNode("192.168.66.119", 16374),
]


# 连接到 MySQL 的 Fixture
@pytest.fixture(scope="module")
def mysql_connection():
    """MySQL连接的Fixture，供整个测试模块使用"""
    connection = mysql.connector.connect(
        host=MYSQL_HOST,
        port=MYSQL_PORT,
        user=MYSQL_USER,
        password=MYSQL_PASSWORD,
        database=MYSQL_DATABASE
    )
    yield connection
    connection.close()


@pytest.fixture(scope="module")
def redis_connection():
    """Redis集群连接的Fixture，供整个测试模块使用"""
    try:
        client = RedisCluster(startup_nodes=REDIS_NODES, decode_responses=True)
        yield client
    except Exception as e:
        pytest.fail(f"Redis 集群连接失败: {e}")


# 测试数据
@pytest.fixture
def red_packet_send_request_data():
    """
    请求体
    """
    return {
        "type": 1,  #   普通红包
        "currency": "usdt",
        "count": 2,
        "amount": str(Decimal("0.0001")),
        # "code": None,  # 让后端生成红包码
        # "phoneCode": "123456",
        "mailCode": "123456",
        # "googleDynamicCode": "789456",
        "blessing": "黄涛脚本测试",
        "expiration": 3,
        "newUserState": 0,  # 0 否
    }


# 测试函数
def test_send_red_packet(red_packet_send_request_data, mysql_connection, redis_connection):
    while True:
        # 处理邮箱验证码的逻辑，这里每次调用接口之前往redis集群里边放一个key
        email_code_redis_key = "user:validateCode:ht@test.com"
        redis_connection.set(email_code_redis_key, 123456)

        # 定义请求头
        headers = {
            "accept-language": "zh-CN",  # 示例语言
            "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbktleSI6InVzZXI6and0OnBjOjIwMjQyMDQyIiwic2FsdCI6ImI3YmU3YjIwZGQzYjRjMzM4YTExNjY3NV8xMDAuOTYuMC4yMzEiLCJsb2dpblR5cGUiOiJwYyIsInNlc3Npb25JZCI6InNoaXJvOnNlc3Npb246cGM6MzAwOGE0MGMtNGQzMS00NjM4LTk1OTEtOTg4YWM0OTQyNjczIiwidXNlck5hbWUiOiJodEB0ZXN0LmNvbSIsImV4cCI6MTczNjgyMzc1MiwidXNlcklkIjoyMDI0MjA0Mn0.mN7KG9LDHZLpsMHXAZ0gQr3YVy2UcXZwgMzteAsx-6c",
        }

        # 定义请求 URL
        url = f"https://test-api.superex.bike/wallet/v3/wallet/red/packet/send"

        # 发起 POST 请求
        response = requests.post(url, json=red_packet_send_request_data, headers=headers)

        # 断言 HTTP 响应状态码为 200
        assert response.status_code == 200, f"Unexpected status code: {response.status_code}"

        # 断言返回数据的结构或内容
        response_data = response.json()
        assert response_data["code"] == 200, "操作失败"

        # 检查返回的数据内容
        red_packet_response = response_data["data"]
        assert "id" in red_packet_response, "返回的数据结构里边没有红包id"
        packet_id = red_packet_response["id"]
        assert packet_id is not None, "Packet ID 不能为空"
        #
        # # 查询 MySQL 数据库，验证红包是否成功创建
        # cursor = mysql_connection.cursor(dictionary=True)
        # query = f"SELECT * FROM red_packet_send WHERE id = {packet_id}"
        # cursor.execute(query)
        #
        # result = cursor.fetchone()
        #
        # # 断言红包在数据库中存在
        # assert result is not None, f"Red packet with ID {packet_id} was not found in the database."
        #
        # # # 验证 MySQL 中的数据
        # # assert result["user_id"] == 12345, "User ID mismatch in the database."
        # # assert result["currency"] == "USD", "Currency mismatch in the database."
        # # assert result["amount"] == Decimal("100.00"), "Amount mismatch in the database."
        #
        # cursor.close()


if __name__ == '__main__':
        test_send_red_packet(red_packet_send_request_data, mysql_connection)
